#coding=utf8
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter

class ImgCode:

    def __init__(self, width, height, num):
       self.width = width
       self.height = height
       self.num = num

    def createImg(self):
        bg_color = self.getRandomColor()
        # 创建一张随机背景色的图片
        img = Image.new(mode="RGB", size=(self.width, self.height), color=bg_color)
        # 获取图片画笔，用于描绘字
        draw = ImageDraw.Draw(img)
        # 修改字体
        font = ImageFont.truetype(font="/var/www/html/python/fonts/SimHei.ttf", size=36)
        for i in range(self.num):
            # 随机生成5种字符+5种颜色
            random_txt = self.getRandomString()
            txt_color = self.getRandomColor()
            # 避免文字颜色和背景色一致重合
            while txt_color == bg_color:
                txt_color = self.getRandomColor()
            # 根据坐标填充文字
            draw.text((10 + 22*i ,5), text=random_txt, fill=txt_color, font=font)
        # 画干扰线点
        self.drawLines(draw)
        self.drawPoints(draw)
        # 打开图片操作，并保存在当前文件夹下
        with open("./image/test.png", "wb") as f:
            img.save(f, format="png")

    def getRandomColor(self):
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        return (r, g, b)

    def getRandomString(self):
        lower = chr(random.randint(97, 122))  # 小写字母a~z
        upper = chr(random.randint(65, 90))  # 大写字母A~Z
        num = str(random.randint(0, 9))
        randomStr = random.choice([num, lower, upper])
        return randomStr

    def drawLines(self, draw):
        for i in range(15):
            x1 = random.randint(0, self.width)
            x2 = random.randint(0, self.width)
            y1 = random.randint(0, self.height)
            y2 = random.randint(0, self.height)
            draw.line((x1, y1, x2, y2), fill = self.getRandomColor())

    def drawPoints(self, draw):
        for i in range(50):
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            draw.point((x,y), fill = self.getRandomColor())


    def getThumbnail(self, path):
        img = Image.open(path)
        img.thumbnail((100,100))
        img.save("./image/thumbnail.png", "png")

    def getFilter(self, path):
        img = Image.open(path)
        img.filter(ImageFilter.BLUR)
        # img.filter(ImageFilter.MinFilter(3))
        # img.filter(ImageFilter.MinFilter)  # same as MinFilter(3)
        img.save("./image/filter.png", "png")




if __name__ == '__main__':
    width = 150
    height = 60
    code = ImgCode(width, height, 6)
    # code.createImg()
    # code.getThumbnail("/var/www/html/python/image/test.jpg")
    # code.getFilter("/var/www/html/python/image/test.jpg")
